//
//  CQiniuFileUpload.m
//  OC_Test_1
//
//  Created by 四小鬼 on 16/9/12.
//  Copyright © 2016年 四小鬼. All rights reserved.
//

#import "CQiniuFileUpload.h"
#import "QNUploadManager.h"
#import "QNUploadOption.h"
#import "GTMBase64.h"
#include <CommonCrypto/CommonCrypto.h>
@interface CQiniuFileUpload ()
{
    
}
@property (nonatomic , assign) int expires;
@end
@implementation CQiniuFileUpload
+ (CQiniuFileUpload *)uploadFile{
    CQiniuFileUpload *upload = [CQiniuFileUpload new];
    return upload;
}

- (id) uploadFileByPath:(NSString *)path progress:(void (^)(CFileUpload *, float))progress finish:(void (^)(CFileUpload *, NSArray *, NSError *))finish{
    CFileModel *model = [self getFileModelWith:path];

    NSString *token = [self getTokenWithName:model.name];
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption *info =[[QNUploadOption alloc]initWithProgressHandler:^(NSString *key, float percent) {
        if (progress) {
            progress(self, percent);
        }
    }];
    [upManager putFile:path key:model.name token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        echo(([NSString stringWithFormat:@"info = %@\n", info]));
        echo(([NSString stringWithFormat:@"key = %@\n",key]));
        echo(([NSString stringWithFormat:@"resp = %@\n", resp]));

        if (finish) {
            CFileModel *model = [self getFileModelWith:path];
            model.size = rand();
            model.uploadpath = key;
            finish(self, @[model], nil);
        }
    } option:info];
    return upManager;
}

- (id)uploadFileByData:(NSData *)data progress:(void (^)(CFileUpload *, float))progress finish:(void (^)(CFileUpload *, NSArray *, NSError *))finish{
    CFileModel *model = [self getFileModelWith:data];
    NSString *token = [self getTokenWithName:model.name];
    QNUploadOption *info =[[QNUploadOption alloc]initWithProgressHandler:^(NSString *key, float percent) {
        if (progress) {
            progress(self, percent);
        }
    }];
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    [upManager putData:data key:model.name token:token complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        echo(([NSString stringWithFormat:@"info = %@\n", info]));
        echo(([NSString stringWithFormat:@"key = %@\n",key]));
        echo(([NSString stringWithFormat:@"resp = %@\n", resp]));

        if (finish) {
            CFileModel *model = [self getFileModelWith:data];
            model.size = rand();
            model.uploadpath = key;
            finish(self, @[model], nil);
        }
    } option:info];
    return self;
}

- (NSString *) getTokenWithName:(NSString*)name{
   // NSString *AK =[CClass getCacheData:qnAk];//@"5sczmEmyO7d-_pou0kR2UOPL3gKY_J9nZTtsCIWY";
   // NSString *SK =[CClass getCacheData:qnSk];
    
    //time_t deadline;
    //time(&deadline);//返回当前系统时间
   // int expires;
//    deadline += (expires > 0) ? expires : 3600; // +3600秒,即默认token保存1小时.
//    
//    NSNumber *deadlineNumber = [NSNumber numberWithLongLong:deadline];
//    
//    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    //文件名字
////    _mp3Name = [NSString stringWithFormat:@"%@_%@.mp3", [Common getDateTimeString], [Common randomStringWithLength:8]];
//   NSString *string =[NSString stringWithFormat:@"%@:%@",[CClass getCacheData:qnScope],name];
//    [dic setObject:string forKey:@"scope"];//根据
//    [dic setObject:deadlineNumber forKey:@"deadline"];
//
//    NSString *json =[Common dictionaryToJson:dic];
//    
//    
//    const char *secretKeyStr = [SK UTF8String];
//    
//    NSString *policy = json;
//    NSData *policyData = [policy dataUsingEncoding:NSUTF8StringEncoding];
//    
//    NSString *encodedPolicy = [GTMBase64 stringByWebSafeEncodingData:policyData padded:TRUE];
//    const char *encodedPolicyStr = [encodedPolicy cStringUsingEncoding:NSUTF8StringEncoding];
//    
//    char digestStr[CC_SHA1_DIGEST_LENGTH];
//    bzero(digestStr, 0);
//    
//    CCHmac(kCCHmacAlgSHA1, secretKeyStr, strlen(secretKeyStr), encodedPolicyStr, strlen(encodedPolicyStr), digestStr);
//    
//    NSString *encodedDigest = [GTMBase64 stringByWebSafeEncodingBytes:digestStr length:CC_SHA1_DIGEST_LENGTH padded:TRUE];
//    
//    //得到token
//    NSString *token = [NSString stringWithFormat:@"%@:%@:%@",  AK, encodedDigest, encodedPolicy];
//    NSLog(@"token%@",token);
//    return token;
    
    
    NSString *AK =[CClass getCacheData:qnAk];//@"5sczmEmyO7d-_pou0kR2UOPL3gKY_J9nZTtsCIWY";
    NSString *SK =[CClass getCacheData:qnSk];
    const char *secretKeyStr = [SK UTF8String];

    time_t deadline;
    time(&deadline);//返回当前系统时间
    deadline += (self.expires > 0) ? self.expires : 3600; // +3600秒,即默认token保存1小时.
    
    NSNumber *deadlineNumber = [NSNumber numberWithLongLong:deadline];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    //users是我开辟的公共空间名（即bucket），aaa是文件的key，
    //按七牛“上传策略”的描述：    <bucket>:<key>，表示只允许用户上传指定key的文件。在这种格式下文件默认允许“修改”，若已存在同名资源则会被覆盖。如果只希望上传指定key的文件，并且不允许修改，那么可以将下面的 insertOnly 属性值设为 1。
    //所以如果参数只传users的话，下次上传key还是aaa的文件会提示存在同名文件，不能上传。
    //传users:aaa的话，可以覆盖更新，但实测延迟较长，我上传同名新文件上去，下载下来的还是老文件。
    [dic setObject:@"users:aaa" forKey:@"scope"];//根据
    NSString *string =[NSString stringWithFormat:@"%@:%@",[CClass getCacheData:qnScope],name];
    [dic setObject:string forKey:@"scope"];//根据
    [dic setObject:deadlineNumber forKey:@"deadline"];
    
    //    NSString *json = [dic JSONString];
    NSString *json =[Common dictionaryToJson:dic];
    NSString *policy=json;
    NSData *policyData = [policy dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *encodedPolicy = [GTMBase64 stringByWebSafeEncodingData:policyData padded:TRUE];
    const char *encodedPolicyStr = [encodedPolicy cStringUsingEncoding:NSUTF8StringEncoding];
    
    char digestStr[CC_SHA1_DIGEST_LENGTH];
    bzero(digestStr, 0);
    
    CCHmac(kCCHmacAlgSHA1, secretKeyStr, strlen(secretKeyStr), encodedPolicyStr, strlen(encodedPolicyStr), digestStr);
    
    NSString *encodedDigest = [GTMBase64 stringByWebSafeEncodingBytes:digestStr length:CC_SHA1_DIGEST_LENGTH padded:TRUE];
    
    NSString *token = [NSString stringWithFormat:@"%@:%@:%@",  AK, encodedDigest, encodedPolicy];
    
    return token;//得到了token
}


@end
